﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using POSSystem.BLL;
using ShopOnline.Controls;
using System.Drawing;
using MyGeneration.dOOdads;
using System.IO;

namespace ShopOnline
{
    public partial class Cart : BasePage
    {
       
        protected void Page_Load(object sender, EventArgs e)
        {
            btnCheckOut.PostBackUrl = POSSystem.BLL.Utilities.GetConfigAppSetting("PayPalURL").ToString();

            ((ProductMaster)this.Master).SetPageTitle("Shopping Cart");
            cart.ReadOnly = false;
            cart.EnablePayPal = true;
            confirmCart.ReadOnly = true;
            
            lblCompanyName.Text = SystemVariables.SysVars.CompanyName;
            lblCompanyAddress.Text = SystemVariables.SysVars.CompanyAddress;
            lblCompanyPhone.Text = SystemVariables.SysVars.CompanyPhone;
            lblDate.Text = DateTime.UtcNow.AddHours(SystemVariables.SysVars.TimeZone).ToString(SystemVariables.SysVars.DateFormat);

            if (!IsPostBack)
            {
                BannerKey = ShopOnline.BLL.BannerKey.Cart;
                if (View_Customers.GetCurrentUser() != null)
                {
                    txtEmail.Text = View_Customers.GetCurrentUser().s_Email;
                    txtAddress.Text = View_Customers.GetCurrentUser().s_Address;
                    txtPhone.Text = View_Customers.GetCurrentUser().s_Phone;
                    txtName.Text = View_Customers.GetCurrentUser().s_CustomerName;
                    txtShipTo.Text = txtAddress.Text;
                    txtShipDate.Text = DateTime.UtcNow.AddHours(SystemVariables.SysVars.TimeZone).ToString(SystemVariables.SysVars.DateFormat);
                }

                UpdateCost();
            }
        }

        private void UpdateCost()
        {
            if (txtVoucherCode.Text == "")
                DiscountAmount = 0;
            else
            {
                View_Vouchers vc = View_Vouchers.GetByCode(txtVoucherCode.Text);
                if (vc.RowCount == 0)
                    DiscountAmount = 0;
                else if (vc.s_DiscountAmount != "")
                    DiscountAmount = vc.DiscountAmount;
                else
                    DiscountAmount = TotalAmount * vc.DiscountPercent / 100;

                if (DiscountAmount > 0)
                {
                    lblDiscount.Text = "<span>Discount: </span><span style='color: red; font-weight: bold' >" + vc.s_Discount + " OFF </span>";
                    lblDiscount.Visible = true;

                    confirmCart.EnablePayPal = true;
                    confirmCart.DiscountAmount = DiscountAmount;
                    confirmCart.Refresh();
                }
            }

            decimal shippingCost = SystemVariables.SysVars.ShippingCost / 2 * (TotalQuantity + 1);
            lblShipping.Text = string.Format("<span>Shipping and Handling: </span><span style='font-weight: bold' >{0:C}</span>", shippingCost);
            lblTotalAmount.Text = string.Format("<span>Total Amount: </span><span style='font-weight: bold' >{0:C}</span>", TotalAmount - DiscountAmount + shippingCost);
        }

        public string GetThankYouURL()
        {
            return string.Format("{0}", POSSystem.BLL.Utilities.GetConfigAppSetting("ThankYou"), OrderKey);
        }

        protected void cart_OnCartChanged(object sender, EventArgs e)
        {
            UpdateCost();
            cart.Refresh();
            confirmCart.Refresh();
            ScriptManager.RegisterStartupScript(this, typeof(Page), Guid.NewGuid().ToString(), "initUI(0);", true);
        }

        public bool UsePayPal()
        {
            return View_Customers.GetCurrentUser() == null || View_Customers.GetCurrentUser().RowCount <= 0 || View_Customers.GetCurrentUser().Price == CustomerType.CustomerPrice.SalePrice;
        }

        public int OrderKey
        {
            get;
            set;
        }

        protected void btnSubmit_OnClick(object sender, EventArgs e)
        {
            if (Cart.SelectedItems.RowCount <= 0)
            {
                ScriptManager.RegisterStartupScript(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("showNotification('All For You Online', 'Nothing to submit!', 8000);", 1), true);
                return;
            }
            TransactionMgr tx = TransactionMgr.ThreadTransactionMgr();
            try
            {
                tx.BeginTransaction();

                CustomerOrders order = new CustomerOrders();
                order.AddNew();
                order.CreatedDate = DateTime.UtcNow.AddHours(SystemVariables.SysVars.TimeZone);
                order.PreferredShipDate = DateTime.Parse(txtShipDate.Text.Trim());
                Sequence seq = new Sequence();
                order.OrderNo = seq.GetNewID("CustomerOrders");
                order.CustomerAddress = txtAddress.Text;
                order.ShipAddress = txtShipTo.Text;
                order.s_CustomerID = View_Customers.GetCurrentUser() != null && View_Customers.GetCurrentUser().RowCount > 0 ? View_Customers.GetCurrentUser().s_ID : "";
                order.s_CustomerName = txtName.Text;
                order.s_CustomerPhone = txtPhone.Text;
                order.Deleted = false;
                order.s_LastModifiedByCustomer = order.s_CustomerID;
                order.GST = cart.TotalGST;
                order.TotalAmount = cart.TotalAmt;
                order.StatusID = OrderStatus.Pending;
                order.PaymentMethodID = UsePayPal() ? PaymentMethod.PayPal : PaymentMethod.BankTransfer;
                order.BranchID = Branches.CurrentBranchID;

                decimal discountAmt = 0;

                if (txtVoucherCode.Text.Trim() != "" && !UsePayPal())
                {
                    string code = txtVoucherCode.Text.Trim();
                    View_Vouchers vc = View_Vouchers.GetByCode(code);
                    if (vc.RowCount >= 0 && vc.Active && !vc.IsUsed && !vc.IsExpired() && (vc.s_Balance == "" || vc.Balance > 0))
                    {
                        order.VoucherID = vc.ID;
                    }
                    else
                        throw new ApplicationException("Invalid Voucher Code or Balance Exceed!");
                }
                else if (txtVoucherCode.Text.Trim() != "")
                {
                    if (txtVoucherCode.Text.Trim() != "")
                    {
                        string code = txtVoucherCode.Text.Trim();
                        View_Vouchers vc = View_Vouchers.GetByCode(code);
                        if (vc.RowCount >= 0 && vc.Active && !vc.IsUsed && !vc.IsExpired() && (vc.s_Balance == "" || vc.Balance > 0))
                        {
                            order.VoucherID = vc.ID;

                            POSSystem.BLL.CustomerOrders submittedOrders = POSSystem.BLL.CustomerOrders.GetPendingOrdersByVoucherId(vc.ID);

                            if (vc.s_DiscountAmount != "")
                            {
                                decimal s = 0;
                                for (int i = 0; i < submittedOrders.RowCount; i++)
                                {
                                    s += submittedOrders.TotalAmount;
                                    submittedOrders.MoveNext();
                                }

                                discountAmt = Math.Min(vc.MultiCheckOut ? Math.Max(vc.Balance - s, 0) : vc.DiscountAmount, order.TotalAmount);
                            }
                            else if (vc.s_DiscountPercent != "")
                            {
                                discountAmt = Math.Min(cart.TotalAmt * vc.DiscountPercent / 100, order.TotalAmount);
                            }
                        }
                        else
                            throw new ApplicationException("Invalid Voucher Code!");
                    }
                }

                order.Save();

                OrderKey = order.ID;

                OrderItems items = BasePage.SelectedItems;
                items.Rewind();
                for (int i = 0; i < items.RowCount; i++)
                {
                    items.OrderID = order.ID;
                    items.s_LastModifiedByCustomer = order.s_LastModifiedByCustomer;
                    items.s_LastModifiedDate = order.s_LastModifiedDate;
                    items.Deleted = false;
                    items.MoveNext();
                }

                items.Save();

                tx.CommitTransaction();

                decimal shippingCost = SystemVariables.SysVars.ShippingCost / 2 * (TotalQuantity + 1);
                BasePage.SelectedItems = new OrderItems();

                try
                {
                    string tempFile = Server.MapPath("~/MailTemplates/NewOrder.htm");
                    string content = File.ReadAllText(tempFile);
                    content = string.Format(content, order.s_CustomerName, order.s_ShipAddress, order.s_CustomerPhone);
                    string recipients = POSSystem.BLL.Utilities.GetConfigAppSetting("AutoMailRecipients");
                    POSSystem.BLL.Utilities.SendEmail(recipients, "New Customer Order", content);
                }
                catch (Exception ex)
                {
                    ErrorLog.WriteToFile("New Customer Order", ex.Message, ex.StackTrace);
                }

                if(discountAmt < order.TotalAmount && UsePayPal())
                {
                    ScriptManager.RegisterStartupScript(this, typeof(Page), Guid.NewGuid().ToString(), string.Format("initUI(2);confirmUserInfo();checkout({0}, {1});", OrderKey, shippingCost), true);
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("showNotification('All For You Online', 'Your order has been submitted successfully. Thank you for supporting us!', 8000);initUI(2, false, false);confirmUserInfo();", 1), true);
                }
            }
            catch (Exception ex)
            {
                tx.RollbackTransaction();
                ErrorLog.WriteToFile("Order.aspx.cs", "lnkSubmit_OnClick", ex.StackTrace);
                ErrorLog.WriteToFile("Order.aspx.cs", "lnkSubmit_OnClick", ex.Message);
                ScriptManager.RegisterStartupScript(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("showErrorAlert('All For You Online', 'There is an error in submitting your order. Please contact administrator for more detail.<br/>Sorry for your inconvenience!', 8000);initUI(2);confirmUserInfo();", 1), true);
            }
        }

        public decimal DiscountAmount
        {
            get
            {
                if (ViewState["DiscountAmount"] == null)
                    ViewState["DiscountAmount"] = (decimal)0;
                return (decimal)ViewState["DiscountAmount"];
            }

            set
            {
                ViewState["DiscountAmount"] = value;
            }
        }

        protected void txtVoucher_OnTextChanged(object sender, EventArgs e)
        {
            lblVoucher.Text = "";
            if (txtVoucherCode.Text == "")
                return;
            
            View_Vouchers vc = View_Vouchers.GetByCode(txtVoucherCode.Text);
            if (vc.RowCount <= 0)
            {
                txtVoucherCode.Text = "";
                ScriptManager.RegisterStartupScript(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("showErrorAlert('All For You Online', 'Invalid Voucher Code!', 8000);initUI(1);", 1), true);
                return;
            }

            if (!vc.Active)
            {
                txtVoucherCode.Text = "";
                ScriptManager.RegisterStartupScript(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("showErrorAlert('All For You Online', 'Voucher Code disabled!', 8000);initUI(1);", 1), true);
                return;
            }

            if (vc.IsUsed)
            {
                txtVoucherCode.Text = "";
                ScriptManager.RegisterStartupScript(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("showErrorAlert('All For You Online', 'Voucher Code has been used!', 8000);initUI(1);", 1), true);
                return;
            }

            decimal s = 0;

            if (!vc.MultiCheckOut)
            {
                POSSystem.BLL.CustomerOrders order = POSSystem.BLL.CustomerOrders.GetPendingOrdersByVoucherId(vc.ID);
                if (order.RowCount > 0)
                {
                    txtVoucherCode.Text = "";
                    ScriptManager.RegisterStartupScript(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("showErrorAlert('All For You Online', 'Voucher Code has been used!', 8000);initUI(1);", 1), true);
                    return;
                }
            }
            else if (vc.s_DiscountAmount != "" && vc.s_Balance != "")
            {
                POSSystem.BLL.CustomerOrders order = POSSystem.BLL.CustomerOrders.GetPendingOrdersByVoucherId(vc.ID);

                for (int i = 0; i < order.RowCount; i++)
                {
                    s += order.TotalAmount;
                    order.MoveNext();
                }

                if (s > vc.Balance || vc.Balance == 0)
                {
                    txtVoucherCode.Text = "";
                    ScriptManager.RegisterStartupScript(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("showErrorAlert('All For You Online', 'Balance Exceed!', 8000);initUI(1);", 1), true);
                    return;
                }
            }

            if (vc.IsExpired())
            {
                txtVoucherCode.Text = "";
                ScriptManager.RegisterStartupScript(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("showErrorAlert('All For You Online', 'Voucher Code expired!', 8000);initUI(1);", 1), true);
                return;
            }

            if (vc.MultiCheckOut && vc.s_DiscountAmount != "" && vc.s_Balance != "")
                lblVoucher.Text = "<span style='color: red; font-weight: bold' >" + string.Format("{0:C}", Math.Max(vc.Balance - s, 0)) + " OFF </span>";
            else
                lblVoucher.Text = "<span style='color: red; font-weight: bold' >" + vc.s_Discount + " OFF </span>";

            lblVoucher.Text += string.Format("<img src='{0}' />", ResolveUrl("~/images/iconBlueCheck.gif"));

            UpdateCost();

            ScriptManager.RegisterStartupScript(this, typeof(Page), Guid.NewGuid().ToString(), string.Format("initUI(1, true);", OrderKey), true);
        }
    }
}